package com.example.servlet.personalServlet;

import com.example.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet("/personalupdate")
public class PersonalUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String currentStudentId = (String) session.getAttribute("studentId");

        if (currentStudentId == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 获取表单数据
        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String grade = request.getParameter("grade");
        String classes = request.getParameter("classes");
        String email = request.getParameter("email");

        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();

            // 验证是否是当前登录用户
            if (!currentStudentId.equals(studentId)) {
                throw new ServletException("无权修改其他用户信息");
            }

            String sql = "UPDATE student SET name=?, grade=?, classes=?, email=? WHERE student_id=?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            stmt.setString(2, grade);
            stmt.setString(3, classes);
            stmt.setString(4, email);
            stmt.setString(5, studentId);

            int rows = stmt.executeUpdate();

            if (rows > 0) {
                session.setAttribute("message", "个人信息更新成功");
                session.setAttribute("messageType", "success");
            } else {
                session.setAttribute("message", "更新失败，请稍后重试");
                session.setAttribute("messageType", "error");
            }

        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("message", "更新失败：" + e.getMessage());
            session.setAttribute("messageType", "error");
        }

        response.sendRedirect("personal");
    }
}